#!/usr/bin/python
# coding=utf-8

import re
import time
import random
import os
import psutil
import subprocess
import chardet
from flask import Flask, render_template, jsonify, request, redirect, url_for
from werkzeug.utils import secure_filename
from datas import get_data


app = Flask(__name__)
app.config.from_object('config')
app.config['UPLOAD_FOLDER'] = 'upload/'


@app.route('/')
def hello_world():
    """
    折线图/柱状图页面
    """
    return render_template('index.html')

@app.route('/multiy')
def multiy():
    """
    多Y轴图
    """
    return render_template('multiy.html')

@app.route('/sharedataset')
def sharedataset():
    """
    联动和共享数据图
    """
    return render_template('sharedataset.html')

@app.route('/contrast')
def contrast():
    """
    三家数据折线图/柱状图页面
    """
    # 计算数据

    return render_template('contrast.html')

idlecpu = []
freemem = []
localtime = []
@app.route('/get_date', methods=["POST"])
def overview_app():
    print(psutil.cpu_percent(interval=1, percpu=True))
    print(psutil.virtual_memory().percent)
    top_info = subprocess.Popen(["top", "-n", "1"], stdout=subprocess.PIPE)
    out, err = top_info.communicate()
    out_info = out.decode("unicode-escape")
    # print(out_info)
    lines = []
    lines = out_info.split("\n")
    localtime.append(time.strftime('%H:%M:%S', time.localtime()))
    for item in lines:
        lowitem = item.strip().lower()
        if "cpu(s)" in lowitem:
            print("itemcpu: ", lowitem)
            wordlist = lowitem.split(",")
            for worditem in wordlist:
                if "id" in worditem:
                    print("idleitem: ", worditem)
                    stritem = worditem.replace("id", "")
                    ascitem = stritem.encode('ascii', 'replace')
                    print("ascitem: ", ascitem)
                    isbegin = False
                    strval = ""
                    for bascii in ascitem:
                        print("bascii:", bascii, chr(bascii))
                        if bascii == 32 and isbegin == False:
                            isbegin = True
                            continue
                        if bascii == 32 and isbegin == True and len(strval) > 0:
                            isbegin = False
                            continue
                        if isbegin == True:
                            strval += chr(bascii)
                    print("idleitem: ", type(stritem), len(stritem), strval, float(strval))
                    idlecpu.append(round(100-float(strval), 2))
        if "mib mem" in lowitem:
            print("itemmem: ", lowitem)
            wordlist = lowitem.split(",")
            for worditem in wordlist:
                if "free" in worditem:
                    print("freemem: ", worditem)
                    stritem = worditem.replace("free", "")
                    ascitem = stritem.encode('ascii', 'ignore')
                    isbegin = False
                    strval = ""
                    for bascii in ascitem:
                        # print("bascii:", bascii, chr(bascii))
                        if bascii == 32 and isbegin == False:
                            isbegin = True
                            continue
                        if bascii == 32 and isbegin == True and len(strval) > 0:
                            isbegin = False
                        if isbegin == True:
                            strval += chr(bascii)
                    print("freemem: ", type(stritem), strval, float(strval))
                    freemem.append(round(100-float(strval)/65317.9*100, 2))

    """
    折线图数据发送
    """
    if request.method == "POST":
        return jsonify(data=[idlecpu,freemem,localtime])


@app.route('/uploader',methods=['GET','POST'])
def uploader():
    if request.method == 'POST':
        f = request.files['file']
        print(request.files)
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))
        return 'file uploaded successfully'
    else:
        return render_template('upload.html')

if __name__ == "__main__":
    app.run(host='0.0.0.0')